package edu.uwlax.cs.oayonlinestore.client.gui.shop;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import edu.uwlax.cs.oayonlinestore.client.OnlinestoreRService;
import edu.uwlax.cs.oayonlinestore.client.Order;
import edu.uwlax.cs.oayonlinestore.client.gui.Store;
import edu.uwlax.cs.oayonlinestore.client.gui.shared.CartTable;
import edu.uwlax.cs.oayonlinestore.client.utils.DefaultAsyncCallback;
import edu.uwlax.cs.oayonlinestore.client.utils.HSpacer;
import edu.uwlax.cs.oayonlinestore.client.utils.SwitchPage;
import edu.uwlax.cs.oayonlinestore.client.utils.TitlePage;

public class PageShoppingCart extends TitlePage {

	private class AddGiftCardHandler extends DefaultAsyncCallback implements
			ClickListener {

		private TextBox text;

		public AddGiftCardHandler(TextBox text) {
			super();
			this.text = text;
		}

		public void onClick(Widget arg0) {
			OnlinestoreRService.Util.getInstance().addGiftCardToOrder(
					Order.get().getId(), text.getText(), this);
		}

		public void onSuccess(Object arg0) {
			cartTable.refresh();
			Order.get().update();
			text.setText("");
		}
	}

	private CartTable cartTable;

	protected void create() {
		setTitle("Shopping Cart");
		add(cartTable = new CartTable());
		add(new HSpacer());
		setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		add(createAddGiftCard());
		add(new HSpacer());
		Button b = new Button("enter payment/shipping information");
		String deliver = Store.getFrame().getShopFrame().getDeliver()
				.getAnchor();
		b.addClickListener(new SwitchPage(deliver));
		add(b);
	}

	private Widget createAddGiftCard() {
		HorizontalPanel hp = new HorizontalPanel();
		TextBox tb = new TextBox();
		hp.add(new HTML("Gift Card ID: "));
		hp.add(tb);
		hp.add(new Button("Use Gift Card", new AddGiftCardHandler(tb)));
		return hp;
	}

	public String getID() {
		return "Cart";
	}

	protected void onShow() {
		cartTable.loadOrder(Order.get().getId());
	}

}